package main

import (
	"context"
	"flag"
	"fmt"
	"gitee.com/scottq/go-framework/grpcProtos/pb"
	"gitee.com/scottq/go-framework/grpcProtos/pb/pb_structs"
	v1config "gitee.com/scottq/go-framework/src/v1/config"
	v1rpc "gitee.com/scottq/go-framework/src/v1/grpcserver"
	v1log "gitee.com/scottq/go-framework/src/v1/log"
	"google.golang.org/grpc"
	"log"
	"os"
	"path/filepath"
)

var port = ""

func init() {
	flag.StringVar(&port, "port", "40001", "rpc lis port")
}

func main() {
	flag.Parse()

	logPath := fmt.Sprintf("./runtime/logs/%s.log", filepath.Base(os.Args[0]))
	logger := v1log.NewZapLog("example", logPath, nil)

	c := &v1config.RpcServerConfig{
		RpcLisAddr: ":" + port,
		RpcRegWay:  "none",
		//RpcRegWay:      "etcd",
		RpcRegServer:   "0.0.0.0:2379",
		RpcRequestAddr: "127.0.0.1:" + port,
	}

	server, err := v1rpc.NewGRPCServer("admin", c)
	if err != nil {
		logger.Error("run server error:%s" + err.Error())
		return
	}
	server.AddLogger(logger)
	server.AddServiceHandler(func(s *grpc.Server) {
		pb.RegisterUserSrServer(s, NewDemoServer())
		pb.RegisterSettingSrServer(s, NewDemo2Server())
	})

	logger.Info("rpc running")
	server.Run()
}

//demo1
type DemoServer struct {
	pb.UnimplementedUserSrServer
}

func NewDemoServer() *DemoServer {
	return &DemoServer{

	}
}

func (s *DemoServer) CheckAuth(ctx context.Context, req *pb.CheckAuthRequest) (*pb.CheckAuthResponse, error) {
	token := req.GetToken()

	return &pb.CheckAuthResponse{
		Code:    1,
		Message: "auth fail " + token,
	}, nil
}

//demo2
type Demo2Server struct {
	pb.UnimplementedSettingSrServer
}

func NewDemo2Server() *Demo2Server {
	return &Demo2Server{

	}
}

var cache = map[string]string{}

func (s *Demo2Server) GetSetting(ctx context.Context, req *pb.GetSettingRequest) (*pb.GetSettingResponse, error) {
	key := req.GetKey()
	if key == "" {
		return &pb.GetSettingResponse{
			Code:    1,
			Message: "key empty ",
		}, nil
	}

	return &pb.GetSettingResponse{
		Code:    0,
		Message: "get success",
		Setting: &pb_structs.Setting{
			Key:   key,
			Value: cache[key],
		},
	}, nil
}
func (s *Demo2Server) SetSetting(ctx context.Context, req *pb.SetSettingRequest) (*pb.SetSettingResponse, error) {
	key := req.GetKey()
	if key == "" {
		return &pb.SetSettingResponse{
			Code:    1,
			Message: "key empty ",
		}, nil
	}
	cache[key] = req.GetValue()
	log.Printf("set: %s=%s", key, req.GetValue())

	return &pb.SetSettingResponse{
		Code:    0,
		Message: "set success",
	}, nil
}
